<template>
  <section class="todoapp">
    <!-- 头部部分 -->
    <my-header @addList="addList"></my-header>
    <!-- 主体部分 -->
    <my-body
      :list="renderList"
      :allList="allList"
      @isDoneStyle="isDoneStyle"
      @delList="delList"
      @allAlter="allAlter"
    ></my-body>

    <!-- 底部部分 -->
    <my-foot
      :list="list"
      @delresidue="delresidue"
      v-show="list.length"
      :type="type"
      @alter="alter"
    ></my-foot>
  </section>
</template>

<script>
import MyBody from './components/MyBody.vue'
import MyFoot from './components/MyFoot.vue'
import MyHeader from './components/MyHeader.vue'
export default {
  components: {
    MyHeader,
    MyBody,
    MyFoot,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('locality')) || [],
      // [
      //   { id: 1, name: '吃饭', isDone: true },
      //   { id: 2, name: '睡觉', isDone: false },
      //   { id: 3, name: '打豆豆', isDone: true },
      // ],
      type: 'all',
    }
  },
  methods: {
    addList(uname) {
      const obj = {
        id: +new Date(),
        name: uname,
        isDone: false,
      }
      this.list = [obj, ...this.list]
    },
    isDoneStyle(id) {
      const obj = this.list.find((item) => item.id === id)
      obj.isDone = !obj.isDone
    },
    delList(id) {
      this.list = this.list.filter((item) => item.id !== id)
    },
    delresidue() {
      this.list = this.list.filter((item) => !item.isDone)
    },
    alter(type) {
      this.type = type
    },
    allAlter(value) {
      this.list.forEach((item) => (item.isDone = value))
    },
  },
  computed: {
    renderList() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.isDone)
        case 'completed':
          return this.list.filter((item) => item.isDone)
        default:
          return this.list
      }
    },
    allList() {
      return this.list.every((item) => item.isDone)
    },
  },
  watch: {
    list: {
      deep: true,
      immediate: true,
      handler(value) {
        localStorage.setItem('locality', JSON.stringify(value))
      },
    },
  },
}
</script>

<style></style>
